package com.test.simplechat.server;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.test.simplechat.config.WebConstants;
import com.test.simplechat.model.WebChatModel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author wen
 * 首次连接是FullHttpRequest，处理参数
 */
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    private final static Logger LOGGER = LoggerFactory.getLogger(HttpRequestHandler.class);
    private String wsPath;

    public HttpRequestHandler(String wsPath) {
        this.wsPath = wsPath;
    }

    public HttpRequestHandler() {
    }

    public String getWsPath() {
        return wsPath;
    }

    public void setWsPath(String wsPath) {
        this.wsPath = wsPath;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
//        LOGGER.debug("ctxId:{}", ctx.channel().id());
        //首次连接是FullHttpRequest，处理参数
        String uri = request.uri();
        GsonBuilder gsonbuilder = new GsonBuilder();
        gsonbuilder.serializeNulls();
        Gson gson = gsonbuilder.create();
        WebChatModel chatModel = null;
        //如果url包含参数，需要处理
        if (uri.contains("?")) {
            String uuid = uri.substring(uri.indexOf("=") + 1);
            uuid = java.net.URLDecoder.decode(uuid, "UTF-8");
            MyChannelHandlerPool.CHANNEL_ID_MAP.put(uuid, ctx.channel().id());
            ctx.channel().attr(WebConstants.CHANNEL_UUID_KEY).setIfAbsent(uuid);
            MyChannelHandlerPool.channelGroup.add(ctx.channel());
            //在线人数统计
            int onlineUserCount = MyChannelHandlerPool.CHANNEL_ID_MAP.keySet().size();
            LOGGER.debug("在线人数:{}", onlineUserCount);
            MyChannelHandlerPool.CHANNEL_ID_MAP.keySet().stream().forEach(i -> System.out.println(i));
            chatModel = new WebChatModel(uuid, "", uuid + "上线", onlineUserCount, WebConstants.MSG_TYPE_PUB);
            request.setUri(wsPath);
        }
        ctx.fireChannelRead(request.retain());

        MyChannelHandlerPool.channelGroup.writeAndFlush(new TextWebSocketFrame(gson.toJson(chatModel)));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
